#!/usr/bin/python
# coding: utf-8
# ===============================================================================
# FILE: temperatureRelay.py
# DESCRIPTION: 树莓派风扇通过继电器当温度达到指定阈值时启动，温度降到阈值一下停止
# AUTHOR: apple1981@126.com
# VERSION: 1.0
# CREATED: 2017-09-28
# ===============================================================================

import sys
import time                     ## 导入time库
import RPi.GPIO as GPIO         ## 导入GPIO库


#温度阈值
temperatureThreshold = 60000
#休眠秒
sleepNum = 5
##温度路径
path = "/sys/class/thermal/thermal_zone0/temp"
# path = "i:/a.txt"
# 使用7号引脚
pin = 7

#初始化函数
def init():
    try:
        print "开始初始化GPIO设置"

        GPIO.setwarnings(False)
        # 使用BOARD引脚编号
        GPIO.setmode(GPIO.BOARD)
        # 设置7号引脚输出
        GPIO.setup(pin,GPIO.OUT)
    except Exception, e:
        print "初始化GPIO引脚出错" + str(e)
        sys.exit(255)
    finally:
        pass


#获取温度信息
def getSystemTemperature():
    try:
        content = open(path,"rb").read()
    except Exception, e:
        print "获取系统温度失败" + str(e)
        GPIO.cleanup()  ## 清除
        sys.exit(255)
    else:
        return content
    finally:
        pass

def processTemperature():
    try:
        while (True):
            currTemperature = getSystemTemperature()
            print "当前系统温度" + currTemperature
            currTemperature = int(currTemperature)
            if(temperatureThreshold<currTemperature):
                print "温度大于阈值,开启风扇"
                updateGpio(1)
            else:
                print "温度小于阈值，关闭风扇"
                updateGpio(0)
            pass
            time.sleep(sleepNum)
        pass
    except Exception, e:
        print "处理温度信息出错" + str(e)
        GPIO.cleanup()  ## 清除
        sys.exit(255)

#设置gpio输出高低电平
def updateGpio(val):
    try:
        if(val==1):
            ## 打开GPIO引脚（HIGH）
            GPIO.output(pin, GPIO.HIGH)
        else:
            ## 关闭GPIO引脚（LOW)
            GPIO.output(pin, GPIO.LOW)
        pass
    except Exception, e:
        print "处理温度信息出错" + str(e)
        GPIO.cleanup() ## 清除
        sys.exit(255)



if __name__ == '__main__':
    init()
    processTemperature()
